package org.execute.tool.虚拟币;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class TronTransactions {
    private static final OkHttpClient client = new OkHttpClient();

    public static List<JSONObject> getTRXTransactions(String address, int limit) throws Exception {
        String url = "https://api.trongrid.io/v1/accounts/" + address + "/transactions?limit=" + limit;
        return fetchTransactions(url);
    }

    public static List<JSONObject> getTRC20Transactions(String address, String contractAddress, int limit) throws Exception {
        String url = "https://api.trongrid.io/v1/accounts/" + address + "/transactions/trc20" +
                "?contract_address=" + contractAddress + "&limit=" + limit;
        return fetchTransactions(url);
    }

    private static List<JSONObject> fetchTransactions(String url) throws Exception {
        Request request = new Request.Builder().url(url).build();
        List<JSONObject> transactions = new ArrayList<>();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new Exception("请求失败: " + response.code());

            String jsonStr = response.body().string();
            JSONObject json = JSON.parseObject(jsonStr);
            JSONArray data = json.getJSONArray("data");
            for (int i = 0; i < data.size(); i++) {
                transactions.add(data.getJSONObject(i));
            }
        }
        return transactions;
    }

    public static void main(String[] args) throws Exception {
        String address = "TA1fCrU4DtvzhAryb8GA7QSfCDq6KxiGGg";
        String usdtContract = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t";

//        // 查询 TRX 交易
//        List<JSONObject> trxTxs = getTRXTransactions(address, 5);
//        System.out.println("TRX 交易记录: " + trxTxs);
//
//        // 查询 USDT-TRC20 交易
//        List<JSONObject> trc20Txs = getTRC20Transactions(address, usdtContract, 5);
//        System.out.println("USDT 交易记录: " + trc20Txs);


        //定时交易记录查询
        Date now = new Date();

        Date yesterday = new Date(now.getTime() - 2*24 * 60 * 60 * 1000);

        boolean received = hasReceivedAmount(
                address,
                usdtContract,
                new BigDecimal("104.83"),
                6,
                yesterday,  // 开始时间
                now         // 结束时间
        );
        System.out.println(received);

    }



    public static List<JSONObject> getTRC20Transactions(String address, String contractAddress,
                                                        Long minTimestamp, Long maxTimestamp,
                                                        int limit) throws Exception {
        // 构建带时间范围的请求URL
        StringBuilder url = new StringBuilder()
                .append("https://api.trongrid.io/v1/accounts/")
                .append(address)
                .append("/transactions/trc20?contract_address=")
                .append(contractAddress);
//                .append("&limit=").append(limit);

        if (minTimestamp != null) {
            url.append("&min_timestamp=").append(minTimestamp);
        }
        if (maxTimestamp != null) {
            url.append("&max_timestamp=").append(maxTimestamp);
        }

        return fetchTransactions(url.toString());
    }

    public static boolean hasReceivedAmount(String address, String contractAddress,
                                            BigDecimal targetAmount, int decimals,
                                            Date startTime, Date endTime) throws Exception {
        // 将时间转换为毫秒时间戳
        Long minTimestamp = startTime != null ? startTime.getTime() : null;
        Long maxTimestamp = endTime != null ? endTime.getTime() : null;

        // 获取带时间范围的交易记录
        List<JSONObject> transactions = getTRC20Transactions(
                address, contractAddress, minTimestamp, maxTimestamp, 50
        );
        System.out.println(transactions);

        // 金额转换（同原逻辑）
        BigDecimal divisor = new BigDecimal(10).pow(decimals);
        String  expectedValue= targetAmount.multiply(divisor).toBigInteger().toString();

        for (JSONObject tx : transactions) {
            // ...原有验证逻辑不变...
            // 增加时间验证（API已过滤，此处可选验证）
            long txTime = tx.getLong("block_timestamp");
            if (startTime != null && txTime < startTime.getTime()) continue;
            if (endTime != null && txTime > endTime.getTime()) continue;

            if (expectedValue.equals(tx.getString("value"))) {
                return true;
            }
            // 原有金额验证逻辑...
        }
        return false;
    }
}